﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Windows.Navigation;
using System.Windows.Controls.Primitives;

namespace Nok_Air
{
    public partial class SelectPassengerPage : PhoneApplicationPage
    {
        private Popup popup;
        private TextBlock SeatNo = null;
        private System.Windows.Controls.Primitives.ToggleButton tgbt = null;
        private string FlightIndexPar = "";
        private string bookingNumberPar = "";
        private string tmpSeatNo = "";
        private int indexFlight = -1;
        private int currentSelPassenger = -1;

        public SelectPassengerPage()
        {
            popup = new Popup();
            popup.Child = new ProgressBarUserControl();
            InitializeComponent();
            DataContext = App.ViewModel;
        }

        private void numberTextBox_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var a = sender as TextBlock;
            if (a.Tag.ToString() == "Y")
            {
                return;
            }

            SeatList.Visibility = System.Windows.Visibility.Visible;
            doneButton.IsEnabled = false;
            SeatNo = a;
            tmpSeatNo = SeatNo.Text;

            int _index = int.Parse(FlightIndexPar);
            string FlightDate = App.ViewModel.GetPassengersResult.Flights[_index].FlightDate;
            FlightDate = string.Format("{0}/{1}/{2}", FlightDate.Substring(8, 2), FlightDate.Substring(5, 2), FlightDate.Substring(0, 4));
            Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
            nokSHelp.GetSeats(App.ViewModel.GetPassengersResult.Flights[_index].FlightNo,
               FlightDate,
                App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].BookingNo,
                App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].ClassCode);
        }

        private void doneButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //int indexFlight = int.Parse(FlightIndexPar);
            string _pasengerXMLString = "";
            foreach (var _passenger in App.ViewModel.GetPassengersResult.Flights[indexFlight].Passengers)
            {
                if (_passenger.CheckInStatus.ToUpper() == "N" && _passenger.SeatNo != "")
                {
                    _pasengerXMLString += string.Format("<Passengers>" +
                      "<RowID>{0}</RowID>" +
                      "<FlightNo>{1}</FlightNo>" +
                      "<FlightDate>{2}</FlightDate>" +
                      "<BookingNo>{3}</BookingNo>" +
                      "<PassengerName>{4}</PassengerName>" +
                      "<PNRNo>{5}</PNRNo>" +
                      "<SeatNo>{6}</SeatNo>" +
                      "<ClassCode>{7}</ClassCode>" +
                      "<MemberID>{8}</MemberID>" +
                      "</Passengers>",
                      _passenger.RowID,
                      App.ViewModel.GetPassengersResult.Flights[indexFlight].FlightNo,
                      App.ViewModel.GetPassengersResult.Flights[indexFlight].FlightDate,
                      _passenger.BookingNo,
                      _passenger.Name,
                      _passenger.PNRNo,
                      _passenger.SeatNo,
                      _passenger.ClassCode,
                      _passenger.MemberID
                      );
                }
            }
            if (_pasengerXMLString == "")
            {
                MessageBox.Show("There are no passengers ready for check in."); return;
            }
            popup.IsOpen = true;
            Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
            nokSHelp.CheckInCompleted += nokSHelp_RequestCompleted;
            nokSHelp.CheckIn(_pasengerXMLString, indexFlight);

        }

        private void SelSeat_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //Change check state former toggleBT
            if (tgbt != null)
            {
                tgbt.IsChecked = false;
            }
            tgbt = sender as System.Windows.Controls.Primitives.ToggleButton;
            //  Grid b = (Grid)tgbt.Parent;
            SeatNo.Text = tgbt.Tag.ToString() + tgbt.Content.ToString();

            CheckInStatus();
        }

        private void ClearSeatBT_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SeatList.Visibility = System.Windows.Visibility.Collapsed;
            SeatNo.Text = tmpSeatNo;
            doneButton.IsEnabled = true;
            CheckInStatus();

        }
        private void CheckInStatus()
        {
            if (App.ViewModel.GetPassengersResult.Flights[indexFlight].Passengers[currentSelPassenger].SeatNo == "")
            {
                App.ViewModel.GetPassengersResult.Flights[indexFlight].Passengers[currentSelPassenger].CheckInStatus = "NS";
            }
            else
            {
                App.ViewModel.GetPassengersResult.Flights[indexFlight].Passengers[currentSelPassenger].CheckInStatus = "N";
            }
        }

        private void DoneSeatBT_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SeatList.Visibility = System.Windows.Visibility.Collapsed;
            doneButton.IsEnabled = true;
        }

        void nokSHelp_RequestCompleted(object sender, WebService.RequestCompletedEventArgs ev)
        {
            if (ev.exception != null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Connection Error");
                    NavigationService.GoBack();
                    NavigationService.Navigated += (ss, ee) =>
                    {
                        popup.IsOpen = false;
                    };
                });
                return;
            }
            Dispatcher.BeginInvoke(() =>
            {
                popup.IsOpen = false;

            });
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.TryGetValue("FlightIndex", out FlightIndexPar) && NavigationContext.QueryString.TryGetValue("bookingNumber", out bookingNumberPar))
            {
                indexFlight = int.Parse(FlightIndexPar);
                PassengerListBox.ItemsSource = App.ViewModel.GetPassengersResult.Flights[indexFlight].Passengers;

                // FlightNo, FlightDate, Bookingno, ClassCode
                // FligthDate must in format *(dd/mm/yyyy)
                // but  App.ViewModel.GetPassengersResult.Flights[_index].FlightDate is in format 2011/05/17
                // then must convert
                string FlightDate = App.ViewModel.GetPassengersResult.Flights[indexFlight].FlightDate;
                FlightDate = string.Format("{0}/{1}/{2}", FlightDate.Substring(8, 2), FlightDate.Substring(5, 2), FlightDate.Substring(0, 4));
                /*   popup.IsOpen = true;
                   Nok_Air.WS.NokAirServicesHelper nokSHelp = new Nok_Air.WS.NokAirServicesHelper();
                   nokSHelp.GetSeatsCompleted += nokSHelp_RequestCompleted;
                   nokSHelp.GetSeats(App.ViewModel.GetPassengersResult.Flights[_index].FlightNo, FlightDate,
                       App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].BookingNo,
                       App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].ClassCode
                   );*/
            }
        }

        private void PassengerListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lbi = sender as ListBox;
            ListBoxItem lbItems = (ListBoxItem)lbi.ItemContainerGenerator.ContainerFromItem(lbi.SelectedItem);
            if (lbItems != null)
            {

                //StackPanel stp = (StackPanel)lbItems.ContentTemplate.LoadContent();
                //Border bder = (Border)stp.Children[0];
                //StackPanel stp2 = (StackPanel)bder.Child;
                //Grid grd = (Grid)stp2.Children[1];
                //Grid grd2 = (Grid)grd.Children[1];
                //TextBlock tb = (TextBlock)grd2.FindName("numberTextBox");
                currentSelPassenger = lbi.SelectedIndex;
                TextBlock tb = FindTreeView(lbItems) as TextBlock;
                if (tb.Tag.ToString() == "Y")
                {
                    NavigationService.Navigate(new Uri("/CheckIn/4BoardingPassPage.xaml?FlightIndex=" + FlightIndexPar + "&PassengersIndex=" + lbi.SelectedIndex, UriKind.Relative));
                    lbi.SelectedIndex = -1;
                    return;
                }

                SeatList.Visibility = System.Windows.Visibility.Visible;
                doneButton.IsEnabled = false;
                SeatNo = tb;
                tmpSeatNo = SeatNo.Text;

                int _index = int.Parse(FlightIndexPar);
                string FlightDate = App.ViewModel.GetPassengersResult.Flights[_index].FlightDate;
                FlightDate = string.Format("{0}/{1}/{2}", FlightDate.Substring(8, 2), FlightDate.Substring(5, 2), FlightDate.Substring(0, 4));
               	Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
                    nokSHelp.GetSeats(App.ViewModel.GetPassengersResult.Flights[_index].FlightNo,
                       FlightDate,
                        App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].BookingNo,
                        App.ViewModel.GetPassengersResult.Flights[_index].Passengers[0].ClassCode);
                   
            }
        }

        public DependencyObject FindTreeView(DependencyObject d_obj)
        {
            if (d_obj == null)
            {
                return null;
            }
            else
            {
                if (d_obj.GetType() == typeof(TextBlock))
                {
                    TextBlock tb = d_obj as TextBlock;
                    if (tb.Name == "numberTextBox")
                    {
                        return tb;
                    }
                }
                else
                {
                    int count = VisualTreeHelper.GetChildrenCount(d_obj);
                    for (int i = 0; i < count; i++)
                    {
                        DependencyObject child = FindTreeView(VisualTreeHelper.GetChild(d_obj, i));
                        if (child != null)
                        {
                            return child;
                        }
                    }
                }
            }
            return null;
        }
    }
}